﻿// FaceAction_demo.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。

#include <iostream>
#include "FaceAction.h"
#include <ctime>

#include <chrono>

using namespace std::chrono;

long long
getMicroSeconds()
{
	auto duration_since_epoch =
	    system_clock::now().time_since_epoch(); // 从1970-01-01 00:00:00到当前时间点的时长
	auto microseconds_since_epoch = duration_cast<microseconds> (duration_since_epoch).count() /
	                                1000; // 将时长转换为微秒数
	return microseconds_since_epoch;
}
int
infer_by_camera (const std::string modelpath, const std::string &window_name = "video")
{
	cv::VideoCapture cap (0);
	
	if (!cap.isOpened()) {
		std::cout << "open camera failed!" << std::endl;
		return 0;
	}
	
	cv::namedWindow (window_name, 1);
	FaceAction fa (modelpath);
	SeetaImageData imgData;
	SeetaRect face;
	SeetaFaceInfoArray face_array;
	cv::Mat frame, canvas;
	int k;
	bool p5 = false;
	bool p68 = false;
	bool showIris = false;
	double fps;
	char string[10];  // 用于存放帧率的字符串
	
	for (; ;) {
		cap >> frame;
		
		if (frame.empty())
			return 0;
			
		auto t0 = getMicroSeconds();
		cv::flip (frame, frame, 1);
		canvas = frame.clone();
		imgData.data = frame.data;
		imgData.width = frame.cols;
		imgData.height = frame.rows;
		imgData.channels = frame.channels();
		face_array = fa.FD->detect (imgData);
		k = cv::waitKey (30);
		cv::Mat showMat = canvas.clone();
		
		//std::cout << "人脸个数为：" << face_array.size << std::endl;
		for (int i = 0; i < face_array.size; i++) {
			face = face_array.data[i].pos;
			fa.init_Mat (canvas, face);
			fa.setPoints68();
			fa.setPoints5();
			
			if (fa.INIT == 1) {
				fa.checkAllAction();
				fa.checkEyeRotation();
			}
			
			if (p5)
				showMat = fa.drawPoints (5, showMat, true);
				
			if (p68)
				showMat = fa.drawPoints (68, showMat, true);
				
			if (showIris)
				showMat = fa.showEyeCenter (showMat);
				
			//fa.getEyeFrame(fa.RIGHT);
			//fa.getEyeCenter();
			//std::cout << fa.getIrisSize(fa.getIrisFrame(fa.EFrame_right, 60)) << std::endl;
		}
		
		if (k == 'q' || k == 'Q') {
			if (p5)
				p5 = false;
			else
				p5 = true;
		}
		
		if (k == 'w' || k == 'W') {
			if (p68)
				p68 = false;
			else
				p68 = true;
		}
		
		if (k == 'E' || k == 'e') {
			if (showIris)
				showIris = false;
			else
				showIris = true;
		}
		
		if (k == 32) {
			fa.init_points (*fa.points5, *fa.points68);
			std::cout << "成功初始化fa" << fa.checkRes.score << std::endl;
		}
		
		auto t1 = (getMicroSeconds() - t0) * 0.001;
		fps = 1 / t1;
		std::string fpsShow = "fps : " + std::to_string (fps);
		cv::putText (showMat, fpsShow, cv::Point (40, 40), cv::FONT_HERSHEY_COMPLEX, 0.5, CV_RGB (255, 0,
		             242), 1);
		cv::imshow (window_name, showMat);
		
		if (k == 27)
			break;
			
	}
	
	cap.release();
	cv::destroyAllWindows();
	return 1;
}
/*
int
main()
{
	std::string modelpath = "models/";
	infer_by_camera (modelpath,
	                 "按Q显示5个检测点，按W显示68个特征点，按空格开始检测人脸动作，按ESC键退出.");
	                 
}
*/